<?php
/**
 * Created by PhpStorm.
 * User: zengyuming
 * Date: 2017/9/12
 * Time: 下午2:47
 */
namespace Api\Controller;
use Think\Controller;
class BankCardNumController extends Controller {
    private $VerifyData = array();
    private $Model;

    public function __construct(){
        parent::__construct();
        $voucherData = BankCardNumController::VerifyOperVoucher(I('post.voucherData'));
        $this->VerifyData = $voucherData;
        $this->Model = M("bankcardnum");
    }

    public function BankCardNumInfo(){
        $bankCode = I('post.bankcode','','strip_tags');
        $result = $this->Model->field("BankAccount,bankCode")->where(array('mch_id' => $this->VerifyData['merchant_id'], 'bankCode' => $bankCode , 'user_id' => $this->VerifyData['user_id']))->select();
        if($result) {
            $this->ajaxReturn(array('error' => 0, 'data' => $result));
        }else{
            $this->ajaxReturn(array('error' => 2, 'data' => ''));
        }
    }

    public function BankCardNumAdd(){
        $bankCode = I('post.bankcode','','strip_tags');
        $BankAccount = I('post.BankAccount','','strip_tags');
        $addData = array(
            'BankAccount' => $BankAccount,
            'mch_id' => $this->VerifyData['merchant_id'],
            'user_id' => $this->VerifyData['user_id']
        );

        $count = $this->Model->where($addData)->count();
        if($count > 0)  exit(json_encode(array('error' => 3 , 'msg' => '该卡号已经存在')));
        $addData['create_begtime'] = time();
        $addData['bankCode'] = $bankCode;
        if(M("bankcardnum")->add($addData)) {
            $this->ajaxReturn(array('error' => 0, 'msg' => '添加成功'));
        }else{
            $this->ajaxReturn(array('error' => 2 , 'msg' => '添加失败，系统错误'));
        }
    }

    public function BankCardNumDel($BankAccount){
        $where = array_merge(array('BankAccount' => strip_tags($BankAccount)),$this->VerifyData);
        unset($where['generateTime']);
        if($this->Model->where($where)->delete()) {
            $this->ajaxReturn(array('error' => 0, 'msg' => '删除成功'));
        }else{
            $this->ajaxReturn(array('error' => 2, 'msg' => '删除失败'));
        }
    }

    /* 验证操作凭证 */
    private static function VerifyOperVoucher($voucherData = array()){
        $VerifyData = json_decode(\Think\Crypt\Driver\Think::decrypt($voucherData , C('encryptKey')),true);
        if(is_array($VerifyData) == false){
            exit(json_encode(array('error' => 1 , 'msg' => '该页面已经过期，请重新发起支付')));
        }
            // Sign认证
            $voucherConfSign = strtoupper(md5($VerifyData['merchant_id'] . $VerifyData['user_id'] . $VerifyData['generateTime'] .  C('SignKey')));
            if($voucherConfSign != $VerifyData['sign']) exit('非法操作');
         return $VerifyData;
    }
}